var app = getApp();
var util = require('../../utils/util.js');
var DB = require('../../utils/db.js');
var QR = require('../../utils/wxqrcode.js');
var size;

Page({

  data: {
    tabbar: ["进出二维码", "进出记录"],
    qrImg:"",
    // phone:"",
    tabIndex: 0,
    // name:"",
    userid:"",
    inoutList: [],
    appear:false,
    limitter:""
  },
  onLoad: function (options) {
    // console.log(options)
    let _this = this;   
    wx.showToast({
      title: '加载中',
      icon:'loading',
      mask:true,
    })
    
    //获取设备size
    this.size = this.getQRCodeSize();
    //通过get_mobile将上个页面传递过来的手机查询用户编号，没有则新建，并setData
    wx.cloud.callFunction({
      name:'get_mobile',
      data:{phone:options.phone},
      success:res=>{
        // console.log(res.result)
        var limitter = _this.doTime(options.limitter,true);  //使用时间戳转换方法转换时间
        _this.setData({
          userid:res.result,
          limitter:limitter,
        })

        //生成二维码
        var date = util.formatTime(new Date());
        var text = res.result + "/" + date;
        _this.createQRCode(text, _this.size)
      }
    })

  },

  // 订阅消息
  // infomation:function(){
  //   var text=this.data.userid+"/"+this.data.time;
  //   var appear = this.data.appear
  //   this.setData({appear:!appear})
  //   this.createQRCode(text, this.size)
  //   wx.cloud.callFunction({
  //     name:"get_student_openid",
  //     data:{
  //      studentID:this.data.userid
  //     }
  //   }).then(res=>{
  //     if(res.result.length==0){
  //       wx.cloud.callFunction({
  //         name:"addoutpeopleopenid",
  //         data:{
  //           allID:this.data.userid,
  //         }
  //       }).then(res=>{
  //         console.log(res)
  //       })
  //     }
  //   })
  //   wx.requestSubscribeMessage({
  //     tmplIds: ['R5pgNdl5ew2oBKdnr3iPLAeWOYUBM9rfUyt9s4qtY1s'],
  //     success: res => {
  //       console.log('success',res)
  //     },
  //     fail: err => {
  //       console.log('err', err)
  //     }
  //   })
  // },
  tomap:function(){
    wx.showToast({
      title: '努力获取中',
      icon: 'loading',
      mask: true
    })
    wx.getImageInfo({     //获取图片信息
      src: 'cloud://epms-aocnh.6570-epms-aocnh-1300754993/school.jpg',
      success(res){
        console.log(res)
        wx.previewImage({    //预览图片
          urls: [res.path],
        })
      }
    })
  },

  onShow: function () {
    //获取时间戳
    // this.time = new Date();
    // var time=this.data.time
    // var localtime = Date.parse(this.time)/ 1000;
    //时间戳转换
    // var date = util.formatTime(new Date());
    // this.setData({ time: date})
    // var num=time-localtime
    // var days=(num/86400).toFixed(0)  //转换为多少天
    // console.log(days)

    // var remain=num%86400
    // var hours=(remain/3600).toFixed(0)
    // console.log(hours)

    // var limitter=days+"天"+hours+"小时"
    // this.setData({
    //   limitter:limitter
    // })
  },

  //上面的tabbar
  tabbar: function (e) {
    const index = e.currentTarget.dataset.index;
    var _this = this
    var userid = _this.data.userid
    this.setData({ tabIndex: index });
    // if (index == 0) {
    //   //生成二维码
    //   this.createQRCode(this.data.userid,this.size)
    // }
    if (index == 1) {
      wx.showToast({
        title: '努力获取中',
        icon: 'loading',
        mask: true
      })
      //获取数据库INorOUT信息
      DB.getInOutByid (userid,function (res) {
        // console.log(res)
        var inoutList = _this.doList(res);
        _this.setData({ inoutList: inoutList })
      })
    }
  },

  //处理数组
  doList: function (list) {
    var timestamp;
    var identity;
    var inout;
    for (var i = 0; i < list.length; i++) {
      list[i].timestamp = this.doTime(list[i].timestamp,false);
      list[i].identity = this.doIdentity(list[i].identity);
      list[i].inorout = this.doInout(list[i].inorout);
    }
    return list.reverse();
  },
  //时间戳转换
  doTime: function (timestamp,isLong) {
    var date = new Date(timestamp * 1000);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate(); d = d < 10 ? ('0' + d) : d;
    var h = date.getHours(); h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds(); minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    if (isLong) { return y+'年'+m + '月' + d + '日 ' + h + ':' + minute + ':'+second;}
    else { return m + '/' + d + ' ' + h + ':' + minute;}
  },
  //身份转换
  doIdentity: function (identity) {
    if (identity == 3) {
      return "外来人员";
    }
  },
  //进出转换
  doInout: function (inout) {
    if (inout == 0) {
      return "正门进校";
    } else if (inout == 1) {
      return "正门出校";
    } else if (inout == 2) {
      return "南门进校";
    } else if (inout == 3) {
      return "南门出校";
    }
  
  },

  //获取设备宽高
  getQRCodeSize: function () {
    var size = 0;
    try {
      var res = wx.getSystemInfoSync();
      var scale = res.windowWidth / 750;
      var width = 300 * scale;
      size = width;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
      size = 150;
    }
    return size;
  },

  //生成二维码
  createQRCode: function (text, size) {
    let that = this
    try {
      // console.log('QRcode: ', text, size)
      let _img = QR.createQrCodeImg(text, {
        size: parseInt(size)
      })
      that.setData({
        qrImg: _img
      })
    } catch (e) {
      console.log(e)
    }
  },
  onPullDownRefresh: function () {
    var date = util.formatTime(new Date());
    var text = this.data.userid + "/" + date;
    this.createQRCode(text, this.size)
    setTimeout(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    }, 1000);
  },
})